# -*-coding:utf-8 -*-
import datetime
import requests
import json
import pandas as pd
from sqlalchemy import create_engine
"""[summary]
通过计算数据之后将数据通过api接口插入到 stock_web工程的数据库中
"""

con = create_engine(
    'mysql+pymysql://root:root@localhost:3306/bao_stock?charset=utf8')

sql_ = "select * from index_0 order by date asc"

base_url = "http://127.0.0.1:8000/"


def make0_post_data(start_date=None, end_date=None):
    # 0号指数
    market0_api = "indicators/market0_api/"
    url_ = base_url+market0_api

    headers = {
        'Content-Type': 'application/json'
    }

    # 获取数据 通过sqlalchemy 和pandas 获取数据 然后循环作用
    m_data = pd.read_sql(sql=sql_, con=con)
    # print(m_data.head(50))
    for i in m_data.index:
        payload = json.dumps({
            "date": m_data['date'][i],
            "open": m_data['open_0'][i],
            "close": m_data['close_0'][i],
            "high": m_data['high_0'][i],
            "low": m_data['low_0'][i],
            "vols": m_data['vol_0'][i],
            "amount": m_data['amount_0'][i],
            "captial": m_data['tq_0'][i]})
        response = requests.request(
            "POST", url_, headers=headers, data=payload)
        print(response.text)

def get_all_date(start_date=None, end_date=None):
        """
        start='2016-06-01'  
        end='2017-01-01'
        """
        if start_date is None and end_date is None:
            return False

        datestart = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        dateend = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        date_list = [datestart.strftime('%Y-%m-%d')]
        while datestart < dateend:
            datestart += datetime.timedelta(days=1)
            date_list.append(datestart.strftime('%Y-%m-%d'))

        return date_list
# make0_post_data()
def makeA_post_data(start_date=None, end_date=None):
    # 0号指数
    marketa_api = "indicators/marcketa_api/"
    url_ = base_url+marketa_api

    headers = {
        'Content-Type': 'application/json'
    }
    
    all_date=get_all_date(start_date=start_date,end_date=end_date)
    for i  in all_date:
        print(i)
        
        sql_ = "select * from kd_data where date='{0}' order by date asc ".format(i)
        # 获取数据 通过sqlalchemy 和pandas 获取数据 然后循环作用
        m_data = pd.read_sql(sql=sql_, con=con)
        if not m_data.empty:
            for i in m_data.index:
                payload = json.dumps({
                    "date": m_data['date'][i],
                    "open": m_data['open'][i],
                    "close": m_data['close'][i],
                    "high": m_data['high'][i],
                    "low": m_data['low'][i],
                    "volume": m_data['volume'][i] if m_data['volume'][i] != '' else 0,
                    "amount": m_data['amount'][i] if m_data['amount'][i] != '' else 0,
                    "code": m_data['code'][i],
                    "preclose": m_data['preclose'][i] if m_data['preclose'][i] !='' else 0,
                    "adjustflag": m_data['adjustflag'][i],
                    "turn": m_data['turn'][i] if m_data['turn'][i] !='' else 0,
                    "tradestatus": m_data['tradestatus'][i],
                    "pctChg": m_data['pctChg'][i],
                    "isST": m_data['isST'][i]

                })
                response = requests.request("POST", url_, headers=headers, data=payload)
                print(response.text)
        

def stock_name():
    api_ = 'indicators/stockname_api/'
    url_ = base_url+api_

    headers = {
        'Content-Type': 'application/json'
    }

    n_data = pd.read_csv(
        './api_data_source/stock_name/沪深Ａ股-板块分类.csv', encoding='gbk')
    n_data.fillna(0, inplace=True)
    n_data.replace(to_replace='--', value=0, inplace=True)
    for i in n_data.index:
        stock_code = '%06d' % n_data['代码'][i]
        stock_name = str(n_data['名称'][i])

        district = str(n_data['地区'][i]).strip()
        market_id = str(n_data['市场代码'][i])
        if n_data['Z-证监会行业'][i]:
            csrc_name = str(n_data['Z-证监会行业'][i]).strip('_')
        else:
            csrc_name = '0'

        if n_data['TDX-证监会行业'][i]:
            tdx_csrc_name = str(n_data['TDX-证监会行业'][i]).strip('_')
        else:
            tdx_csrc_name = '0'
        if n_data['TDX-一级行业'][i]:

            tdx_1ind = str(n_data['TDX-一级行业'][i]).strip('_')
        else:
            tdx_1ind = '0'
        if n_data['细分行业'][i]:
            tdx_2ind = str(n_data['细分行业'][i]).strip()
        else:
            tdx_2ind = '0'

        if n_data['Z-概念'][i]:
            concept = str(n_data['Z-概念'][i]).strip('_').split('_')
        else:
            concept = []
        if n_data['Z-风格'][i]:
            style = str(n_data['Z-风格'][i]).strip('_').split('_')
        else:
            style = []
        if n_data['Z-指数'][i]:
            exponent = str(n_data['Z-指数'][i]).strip('_').split('_')
        else:
            exponent = []

        if n_data['上市日期'][i]:

            listingdate = str(n_data['上市日期'][i])
            listingdate = listingdate[0:4]+'-' + \
                listingdate[4:6]+'-'+listingdate[6:]
        else:
            listingdate = '0'

        payload = json.dumps({
            "stock_code": stock_code,
            "stock_code_name": stock_name,
            "stock_market_id": market_id,
            "district": district,
            "tdx2ind_plate": tdx_1ind,
            "tdx1ind_plate": tdx_2ind,
            "tdxcsrc_plate": tdx_csrc_name,
            "csrc_plate": csrc_name,
            "concept_plate": concept,
            "styles_plate": style,
            "exponent_plate": exponent,
            "listing_date": listingdate,
        })
        response = requests.request(
            "POST", url_, headers=headers, data=payload)

        print(response.text)
        # print(stock_code,stock_name,district,csrc_name,tdx_csrc_name,tdx_1ind,tdx_2ind,concept,style,exponent,listingdate)

    # print(n_data.head(50))

# stock_name()

# data=pd.read_csv('./api_data_source/stock_name/沪深A股_概念_20210701.txt',encoding='gbk')
# data.to_csv('./api_data_source/stock_name/zhha.csv')


makeA_post_data(start_date="2020-06-10",end_date='2020-06-15')

